<template>
  <div class="lab-application">
    <div class="table-header">
      <h3>实验室申请列表</h3>
    </div>

    <div class="selcart">
      <a-space align="center">
        <!-- <span style="margin-left: 15px">学期</span>
        <a-select
          v-model:value="filterParams.semesterId"
          placeholder="请选择学期"
          style="width: 130px"
          allowClear="true"
        >
          <a-select-option
            v-for="semester in semesters"
            :key="semester.value"
            :value="semester.value"
          >
            {{ semester.label }}
          </a-select-option>
        </a-select> -->

        <span style="margin-left: 15px">周次</span>
        <a-select
          v-model:value="filterParams.week"
          placeholder="请选择周次"
          style="width: 130px"
          allowClear="true"
        >
          <a-select-option
            v-for="week in weeks"
            :key="week.value"
            :value="week.value"
          >
            {{ week.label }}
          </a-select-option>
        </a-select>

        <span style="margin-left: 15px">星期</span>
        <a-select
          v-model:value="filterParams.day"
          placeholder="请选择星期"
          style="width: 130px"
          allowClear="true"
        >
          <a-select-option
            v-for="day in daysOfWeek"
            :key="day.value"
            :value="day.value"
          >
            {{ day.label }}
          </a-select-option>
        </a-select>

        <span style="margin-left: 15px">节次</span>
        <a-select
          v-model:value="filterParams.session"
          placeholder="请选择节次"
          style="width: 130px"
          allowClear="true"
        >
          <a-select-option
            v-for="session in sessions"
            :key="session.value"
            :value="session.value"
          >
            {{ session.label }}
          </a-select-option>
        </a-select>

        <span style="margin-left: 15px">实验室类型</span>

        <a-select
          v-model:value="filterParams.labType"
          placeholder="请选择实验室类型"
          style="width: 150px"
          allowClear="true"
        >
          <a-select-option
            v-for="labType in labTypes"
            :key="labType.value"
            :value="labType.value"
          >
            {{ labType.label }}
          </a-select-option>
        </a-select>

        <a-button type="primary" @click="search">查询</a-button>
      </a-space>
    </div>

    <a-table
      :columns="columns"
      :data-source="dataSource"
      bordered
      size="small"
      :pagination="true"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space wrap>
            <a-button
              size="small"
              type="primary"
              :disabled="record.status === 1"
              @click="showApplyModal(record)"
              >申请</a-button
            >
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal
      v-model:visible="isApplyModalVisible"
      :title="modalConfig.title"
      @ok="submitApplyLab"
      @cancel="closeApplyModal"
      centered="true"
    >
      <a-form-item label="申请理由" :rules="[requiredRule]">
        <a-input v-model:value="reason" />
      </a-form-item>
    </a-modal>

    <a-modal
      v-model:visible="isCancelModalVisible"
      :title="modalConfig.cancelTitle"
      @ok="submitCancelLab"
      @cancel="closeCancelModal"
      centered="true"
    >
      <p>确认撤销申请吗？</p>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue";
import { type Ilab, type ILabApply } from "@/api/RequestIDL/labType";
import { filter, omit } from "lodash";
import { labQuery, labApply } from "@/api/methods/studentReq";
import { labTypeQuery } from "@/api/methods/labReq";
import { semesterAll } from "@/api/methods/semesterReq";
import { Item } from "ant-design-vue/es/menu";
import { userInfo, userInfoJson } from "@/utils/userInfo";
import { useLocalStorage } from "@vueuse/core";
import { labInfo } from "@/utils/userInfo";

const semesterId = useLocalStorage<string>("semesterId", "");
const semesterName = useLocalStorage<string>("semesterName", "");

const isApplyModalVisible = ref(false);
const isCancelModalVisible = ref(false);
const selectedLab = ref({
  day: null,
  id: null,
  labId: null,
  labName: "",
  reason: "",
  semesterId: semesterId.value,
  semesterName: semesterName.value,
  session: null,
  state: null,
  week: null,
  studentId: null,
  studentName: "",
});

const reason = ref("");
const modalConfig = {
  title: "请填写申请理由",
  cancelTitle: "撤销申请确认",
};

const requiredRule = {
  required: true,
  message: "申请理由不能为空",
  trigger: "blur",
};

const showApplyModal = (lab: ILabApply) => {
  isApplyModalVisible.value = true;
  selectedLab.value = lab;
};

const closeApplyModal = () => {
  isApplyModalVisible.value = false;
};

const closeCancelModal = () => {
  isCancelModalVisible.value = false;
};

const submitApplyLab = async () => {
  isApplyModalVisible.value = false;

  const queryParams = {
    id: selectedLab.value?.id,
    reason: reason.value,
    labId: selectedLab.value?.labId || "--",
    semesterId: selectedLab.value?.semesterId,
    week: selectedLab.value?.week,
    session: selectedLab.value?.session,
    day: selectedLab.value?.day,
    studentId: userInfo.value.id,
    state: 1,
  };

  try {
    await labApply(queryParams);
  } catch (error) {
    console.error("Error applying for the lab:", error);
  }
  reload();
};

async function reload() {
  if (filterParams.value.semesterId == semesterName.value) {
    filterParams.value.semesterId = semesterId.value;
  }
  const queryParams: LabQueryParams = {
    semesterId: filterParams.value.semesterId,
    week: filterParams.value.week,
    day: filterParams.value.day,
    session: filterParams.value.session,
    labType: filterParams.value.labType,
    page: pageConfig.value.page,
    pageSize: pageConfig.value.pageSize,
  };
  const result = await labQuery(queryParams);
  dataSource.value = result.data.map((item: any) => {
    return {
      ...(item || null),
    };
  });
}

const columns = [
  {
    title: "申请实验室",
    dataIndex: "labId",
    key: "labId",
    width: "170px",
    customRender: ({ text, record, index, column }) => {
      return translateLabId(text);
    },
  },
  { title: "申请学期", dataIndex: "semesterName", key: "semesterName" },
  {
    title: "周次",
    dataIndex: "week",
    key: "week",
    customRender: ({ text, record, index, column }) => {
      return "第" + text + "周";
    },
  },
  {
    title: "星期",
    dataIndex: "day",
    key: "day",
    customRender: ({ text, record, index, column }) => {
      switch (text) {
        case 1:
          return "周一";
        case 2:
          return "周二";
        case 3:
          return "周三";
        case 4:
          return "周四";
        case 5:
          return "周五";
        case 6:
          return "周六";
        case 7:
          return "周日";
        default:
          return "--";
      }
    },
  },
  {
    title: "节次",
    dataIndex: "session",
    key: "session",
    customRender: ({ text, record, index, column }) => {
      switch (text) {
        case 1:
          return "1-2";
        case 2:
          return "3-5";
        case 3:
          return "6-7";
        case 4:
          return "8-9";
        case 5:
          return "10-12";
        case 6:
          return "13-15";
        default:
          return "--";
      }
    },
  },
  // { title: "实验室类型", dataIndex: "labType", key: "labType" },
  {
    title: "使用情况",
    dataIndex: "state",
    key: "state",
    customRender: ({ text, record, index, column }) => {
      switch (text) {
        case 0:
          return "空闲";
        case 1:
          return "申请中";
        case 2:
          return "已拒绝";
        default:
          return "--";
      }
    },
  },
  { title: "操作", dataIndex: "action", key: "action", width: "160px" },
];

const labTypes = ref([]);

const semesters = ref();

const dataSource = ref();

const weeks = [
  { value: "1", label: "第1周" },
  { value: "2", label: "第2周" },
  { value: "3", label: "第3周" },
  { value: "4", label: "第4周" },
  { value: "5", label: "第5周" },
  { value: "6", label: "第6周" },
  { value: "7", label: "第7周" },
  { value: "8", label: "第8周" },
  { value: "9", label: "第9周" },
  { value: "10", label: "第10周" },
  { value: "11", label: "第11周" },
  { value: "12", label: "第12周" },
  { value: "13", label: "第13周" },
  { value: "14", label: "第14周" },
  { value: "15", label: "第15周" },
  { value: "16", label: "第16周" },
  { value: "17", label: "第17周" },
  { value: "18", label: "第18周" },
  { value: "19", label: "第19周" },
  { value: "20", label: "第20周" },
  { value: "21", label: "第21周" },
  { value: "22", label: "第22周" },
];

const daysOfWeek = [
  { value: "1", label: "星期一" },
  { value: "2", label: "星期二" },
  { value: "3", label: "星期三" },
  { value: "4", label: "星期四" },
  { value: "5", label: "星期五" },
  { value: "6", label: "星期六" },
  { value: "7", label: "星期日" },
];

const sessions = [
  { value: "1", label: "1-2" },
  { value: "2", label: "3-5" },
  { value: "3", label: "6-7" },
  { value: "4", label: "8-9" },
  { value: "5", label: "10-12" },
  { value: "6", label: "13-15" },
];

const filterParams = ref({
  semesterId: "",
  week: "",
  day: "",
  session: "",
  labType: "",
});

const loading = ref(false);

const pageConfig = ref({
  pageSize: 10,
  page: 1,
  total: 0,
});

interface IPagenation {
  current: number;
  pageSize: number;
  total: number;
}

const handleTableChange = async (pagination: IPagenation) => {
  pageConfig.value.page = pagination.current;
  pageConfig.value.pageSize = pagination.pageSize;
  loading.value = true;
  const res = await labQuery({
    page: pageConfig.value.page,
    pageSize: pageConfig.value.pageSize,
    semesterId: "",
    week: "",
    day: "",
    session: "",
    labType: "",
  });
  dataSource.value = res.data;
  loading.value = false;
};

interface LabQueryParams {
  semesterId: string;
  week: string;
  day: string;
  session: string;
  labType: string;
  page: number;
  pageSize: number;
}

onMounted(async () => {
  try {
    const labTypeResult = await labTypeQuery({});
    const labTypeOptions = labTypeResult.data.map((type: any) => ({
      value: type.id,
      label: type.typeName,
    }));
    labTypes.value = labTypeOptions;
  } catch (error) {
    console.error("Error fetching lab types:", error);
  }
});

onMounted(async () => {
  try {
    const semesterResult = await semesterAll({});
    const semesterOptions = semesterResult.data.map((semester: any) => ({
      value: semester.id,
      label: semester.name,
    }));
    semesters.value = semesterOptions;
    filterParams.value.semesterId = semesterOptions.find(
      (item: any) => item.label === semesterName.value
    ).value;
  } catch (error) {
    console.error("Error fetching semesters:", error);
  }
});

onMounted(async () => {
  loading.value = true;
  const res = await labQuery({
    page: pageConfig.value.page,
    pageSize: pageConfig.value.pageSize,
    semesterId: "",
    week: "",
    day: "",
    session: "",
    labType: "",
  });
  dataSource.value = res.data.map((item: any) => {
    return {
      ...(item || null),
    };
  });
  loading.value = false;
});

async function search() {
  try {
    const queryParams: LabQueryParams = {
      semesterId: filterParams.value.semesterId,
      week: filterParams.value.week,
      day: filterParams.value.day,
      session: filterParams.value.session,
      labType: filterParams.value.labType,
      page: pageConfig.value.page,
      pageSize: pageConfig.value.pageSize,
    };

    const result = await labQuery(queryParams);
    dataSource.value = result.data.map((item: any) => {
      return {
        ...(item || null),
      };
    });

    loading.value = false;
  } catch (error) {
    console.error("查询实验室申请列表时发生错误:", error);

    loading.value = false;
  }
}

function translateLabId(text) {
  const labName = labInfo.value.find((i) => i.id === text).name;
  return labName || "名字不存在";
}
</script>

<style scoped lang="scss">
.lab-application {
  .selcart {
    height: 80px;
    display: flex;
    background-color: white;
    justify-content: left;
    border-radius: 10px;
    margin-bottom: 10px;
  }
  .table-header {
    text-align: center;

    h3 {
      text-align: center;
    }
  }
}
</style>
